package com.bing.Impl;

import com.bing.beans.Person;
import com.bing.beans.Search;
import com.bing.beans.WeiBo;
import com.bing.sina.SinaJdbc;
import com.bing.util.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.FileNotFoundException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2014/6/20.
 */

@Component
public class GetWeiBoStep extends AbstrcatStep {
    private static final Logger logger = LoggerFactory.getLogger(GetWeiBoStep.class);
    private String weiboContent;
    private ExecutorService executorService;
    private ExcelUtil excelUtil;
    @Autowired
    private SinaJdbc sinaJdbc;
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");


    @Override
    public void preStart(Context context) {
        super.preStart(context);
        logger.info("开始获取特定微博内容...........");
        weiboContent = ((List<String>) context.getSetting(Context.WEIBOID)).get(0);
        executorService = Executors.newFixedThreadPool(4);
        try {
            excelUtil = new ExcelUtil(weiboContent);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void end(Context context) {
        super.end(context);
        logger.info("结束获取特定微博内容...........");
    }

    @Value("#{sina['step.getWeiBo.process']}")
    public void setProcess(Boolean process) {
        super.setProcess(process);
    }

    /**
     * 登陆淘大客,获取淘大客资料
     */
    @Override
    public void exec(Context context) {
        Search search = new Search();
        search.setSearchContent(weiboContent);
        search.setsTime(new Date());
        sinaJdbc.saveSearch(search);
        Date startDate = (Date) context.getSetting(Context.START_DATA);
        Date endDate= (Date) context.getSetting(Context.END_DATA);
        for (int i = 1; ; i++) {
            String res = String.format(Context.Search_WeiBo, weiboContent, startDate,endDate, i);
            logger.info("获取内容网址: {}", res);
            driver.get(res);
            TaoBao.pause(7000);
            String html = driver.getPageSource();
            Document doc = Jsoup.parse(html);
            Elements elements = doc.select("#plc_main #pl_wb_feedlist .pl_noresult .search_noresult");
            Elements weibos = doc.select("#plc_main #pl_wb_feedlist .feed_list");
            if (elements.size() != 0 || weibos.size() == 0) {
                logger.info("没有找到相关内容");
                break;
            } else {
                search(weibos, search);
            }
        }
        taoListener.setStatus("采集微薄内容完毕");
        excelUtil.closeWrite();

    }

    private void search(Elements weiBos, Search search) {
        Person person = null;
        for (Element element : weiBos) {
            WeiBo weiBo = new WeiBo();
            String url = element.select("dt.face a").get(0).attr("href");  //http://weibo.com/u/2398736561
            url = TaoMath.getWeiBoPersonUrl(url);

            String content = element.select("dd.content em").get(0).text();
            String weiBoUrl = element.select("dd.content p.info a.date").get(0).attr("href");
            String weiBoTime = element.select("dd.content p.info a.date").get(0).attr("title"); //2014-08-30 11:13
            String zanZhangFa = element.select("dd.content p.info span").text(); //赞| 转发(1)| 收藏| 评论
            weiBo.setContent(content);

            try {
                weiBo.setCreate_date(sdf.parse(weiBoTime));
            } catch (ParseException e) {
                weiBo.setCreate_date(new Date());
            }
            weiBo.setUrl(weiBoUrl);
            TaoMath.setZanZhuangFa(weiBo, zanZhangFa);

            person = sinaJdbc.findPerson(url);
            if (person == null) {
                person = new Person();
                person.setUrl(url);
                getPerson(person);
            }
            weiBo.setPerson(person);
            if (weiBo.getPingLun() != 0) {
                logger.info("微博:{} 评论数:{},地址:{}", weiBo.getUrl(), weiBo.getPingLun(), weiBoUrl + "?type=comment");
                Set<String> pingLuns = new HashSet<String>();
                driver.get(weiBoUrl + "?type=comment");
                TaoBao.switchLast(driver);
                String pingLunHtml = driver.getPageSource();
                Document doc = Jsoup.parse(pingLunHtml);
                Elements elements = doc.select("div.WB_media_expand[node-type=comment_detail] .comment_lists .comment_list dd");
                for (Element e : elements) {
                    pingLuns.add(e.text());
                    logger.info("评论:{}", e.text());
                }
                weiBo.setPingLuns(pingLuns);
            }
            if (weiBo.getZhuangFa() != 0) {
                logger.info("微博:{} 转发数:{}", weiBo.getUrl(), weiBo.getZhuangFa());
                driver.get(weiBoUrl + "?type=repost");
                String zhuangFaHtml = driver.getPageSource();
                Document doc = Jsoup.parse(zhuangFaHtml);
                Elements elements = doc.select("div.WB_media_expand[node-type=forward_detail] .comment_lists dl dt a");
                Person zhuangFaPerson;
                int zhangFaShuHe = 0;
                for (Element e : elements) {
                    String zhuangFaPersonUrl = e.attr("href").replace("/", "");
                    zhuangFaPerson = sinaJdbc.findPerson(zhuangFaPersonUrl);
                    if (zhuangFaPerson == null) {
                        zhuangFaPerson = new Person();
                        zhuangFaPerson.setUrl(zhuangFaPersonUrl);
                        getPerson(zhuangFaPerson);
                        zhangFaShuHe += zhuangFaPerson.getFenSi();
                        logger.info("转发人粉丝数:{}", zhuangFaPerson.getFenSi());
                    }
                }
                weiBo.setZhuangFaFenSiHe(zhangFaShuHe);
            }

            excelUtil.writeWeiBoContent(weiBo);
            weiBo.setSearch(search);
            sinaJdbc.saveWeiBo(weiBo);
        }
    }

    private void getPerson(Person p) {
        for (int i = 0; i <= 3; i++) {
            logger.info("采集用户{} 信息.....尝试第{}次", p.getUrl(), i);
            try {
                driver.get(Context.PRE_WEIBO + p.getUrl());
                WebElement level = driver.findElement(By.cssSelector("div.profile_top div.pf_name div.icon_bed[node-type=level]"));
                Actions action = new Actions(driver);
                action.moveToElement(level).build().perform();
                TaoBao.pause();
                PersonParse personParse = new PersonParse(driver.getPageSource(), p, taoListener);
                personParse.run();
                sinaJdbc.savePerson(p);
                break;
            } catch (Exception e) {
                if (e instanceof NoSuchElementException) {
                }
                if (i == 3) {
                    logger.error("采集人物失败", e);
                }
            }
        }
    }

    @Autowired
    @Qualifier("endStep")
    public void setNextStep(AbstrcatStep nextStep) {
        super.setNextStep(nextStep);
    }

}
